/**
 * 依赖分析器模板文件
 * 包含所有生成 HTML 的模板函数
 */
import * as vscode from 'vscode';
import { Dependency } from '../dependencyAnalyzer';
import { getGlobalFunctionsScript } from './globalFunctions';

/**
 * 生成依赖冲突表格的HTML
 */
export function generateConflictsTableHtml(conflicts: Dependency[], pomPath: string, escapeHtmlFunc: (text: string) => string, getSafeIdFunc: (text: string) => string): string {
    if (conflicts.length === 0) {
        return '<div class="no-conflicts">没有发现依赖冲突</div>';
    }
    
    let html = `
        <table>
            <thead>
                <tr>
                    <th>GroupId</th>
                    <th>ArtifactId</th>
                    <th>版本</th>
                    <th>冲突版本</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="conflicts-table-body">
    `;
    
    for (const dep of conflicts) {
        const conflictVersions = dep.conflicts?.map(c => c.version && c.version.trim() ? c.version : '未指定').join(', ');
        const displayVersion = dep.version?.trim() ? dep.version : '未指定';
        const safeId = getSafeIdFunc(`${dep.groupId}:${dep.artifactId}`);
        
        html += `
            <tr class="conflict-row" data-group-id="${escapeHtmlFunc(dep.groupId)}" data-artifact-id="${escapeHtmlFunc(dep.artifactId)}">
                <td>${escapeHtmlFunc(dep.groupId)}</td>
                <td>${escapeHtmlFunc(dep.artifactId)}</td>
                <td class="version-cell">${escapeHtmlFunc(displayVersion)}</td>
                <td>${escapeHtmlFunc(conflictVersions ?? '')}</td>
                <td>
                    <button class="action-btn view-details-btn" data-path="${escapeHtmlFunc(dep.path.join(':'))}" data-id="${safeId}">查看详情</button>
                    <button class="action-btn exclude-btn" data-group-id="${escapeHtmlFunc(dep.groupId)}" data-artifact-id="${escapeHtmlFunc(dep.artifactId)}" data-pom-path="${escapeHtmlFunc(pomPath)}">排除</button>
                </td>
            </tr>
        `;
    }
    
    html += `
            </tbody>
        </table>
    `;
    
    return html;
}

/**
 * 生成依赖表格行的HTML
 */
export function generateDependenciesTableRowsHtml(dependencies: Dependency[], pomPath: string, escapeHtmlFunc: (text: string) => string): string {
    let html = '';
    for (const dep of dependencies) {
        const displayVersion = dep.version?.trim() ? dep.version : '未指定';
        
        html += `
            <tr class="dependency-row" data-group-id="${escapeHtmlFunc(dep.groupId)}" data-artifact-id="${escapeHtmlFunc(dep.artifactId)}">
                <td>${escapeHtmlFunc(dep.groupId)}</td>
                <td>${escapeHtmlFunc(dep.artifactId)}</td>
                <td>${escapeHtmlFunc(displayVersion)}</td>
                <td class="dep-scope">${escapeHtmlFunc(dep.scope ?? 'compile')}</td>
                <td>
                    <button class="action-btn view-details-btn" data-path="${escapeHtmlFunc(dep.path.join(':'))}" data-group-id="${escapeHtmlFunc(dep.groupId)}" data-artifact-id="${escapeHtmlFunc(dep.artifactId)}">查看详情</button>
                    <button class="action-btn exclude-btn" data-group-id="${escapeHtmlFunc(dep.groupId)}" data-artifact-id="${escapeHtmlFunc(dep.artifactId)}" data-pom-path="${escapeHtmlFunc(pomPath)}">排除</button>
                </td>
            </tr>
        `;
    }
    return html;
}

/**
 * 生成依赖表格的HTML
 */
export function generateDependenciesTableHtml(dependencies: Dependency[], pomPath: string, escapeHtmlFunc: (text: string) => string, paging?: {pageSize: number, totalSize: number, showLoadMore: boolean}): string {
    let html = `
        <table>
            <thead>
                <tr>
                    <th>GroupId</th>
                    <th>ArtifactId</th>
                    <th>版本</th>
                    <th>作用域</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="dependencies-table-body">
    `;
    html += generateDependenciesTableRowsHtml(dependencies, pomPath, escapeHtmlFunc);
    html += `
            </tbody>
        </table>
    `;
    if (paging?.showLoadMore) {
        html += `
            <div class="load-more-container">
                <button class="load-more-btn" id="load-more">加载更多 (${paging.pageSize} / ${paging.totalSize})</button>
            </div>
        `;
    }
    return html;
}

/**
 * 生成简化的依赖树HTML
 */
export function generateSimplifiedDependencyTreeHtml(dependencies: Dependency[], pomPath: string, escapeHtmlFunc: (text: string) => string, escapeAttrValueFunc: (text: string) => string): string {
    console.log("生成简化依赖树...");
    const rootDeps = dependencies.filter(d => d.path.length === 0);
    console.log(`根依赖数量: ${rootDeps.length}`);
    
    let html = `
        <style>
            .tree-view {
                font-family: monospace;
                line-height: 1.6;
            }
            .root-dep {
                margin-bottom: 15px;
                padding-bottom: 5px;
                border-bottom: 1px solid var(--vscode-panel-border);
            }
            .dep {
                margin-left: 20px;
                position: relative;
            }
            .dep-line {
                display: flex;
                align-items: center;
                white-space: nowrap;
                padding: 2px 0;
            }
            .dep-name {
                margin-right: 10px;
                font-weight: bold;
            }
            .dep-version {
                color: #0078d4;
                margin-right: 10px;
                font-weight: bold;
            }
            .dep-scope {
                color: #6c6c6c;
                margin-right: 10px;
                font-style: italic;
            }
            .conflict {
                color: #e51400;
            }
            .actions {
                margin-left: auto;
                opacity: 0.7;
            }
            .actions:hover {
                opacity: 1;
            }
            .action-btn {
                background: none;
                border: none;
                cursor: pointer;
                color: var(--vscode-textLink-foreground);
                padding: 2px 5px;
                text-decoration: underline;
            }
            .summary {
                margin-bottom: 15px;
                padding: 10px;
                background-color: var(--vscode-editor-inactiveSelectionBackground);
                border-radius: 4px;
            }
            .search-container {
                display: flex;
                margin-bottom: 10px;
            }
            .search-box {
                width: 100%;
                padding: 8px;
                box-sizing: border-box;
                border: 1px solid var(--vscode-input-border);
                background-color: var(--vscode-input-background);
                color: var(--vscode-input-foreground);
            }
            .search-button {
                margin-left: 5px;
                background-color: var(--vscode-button-background);
                color: var(--vscode-button-foreground);
                border: none;
                padding: 6px 12px;
                cursor: pointer;
            }
            .search-button:hover {
                background-color: var(--vscode-button-hoverBackground);
            }
            .no-results {
                padding: 20px;
                text-align: center;
                color: var(--vscode-disabledForeground);
            }
            .children-container {
                margin-left: 20px;
            }
            .dep-name.highlight {
                color: #e51400;
                font-weight: bold;
                background-color: rgba(229, 20, 0, 0.1);
                padding: 2px 4px;
                border-radius: 3px;
            }
            .search-match {
                color: #e51400;
                font-weight: bold;
                background-color: rgba(229, 20, 0, 0.1);
                padding: 2px 4px;
                border-radius: 3px;
            }
            .parent-of-match {
                opacity: 1 !important;
            }
            .search-hidden {
                display: none;
            }
            .dep-path {
                color: #6c6c6c;
                font-size: 0.9em;
                display: block;
                margin-top: 4px;
                margin-bottom: 6px;
                padding-left: 20px;
            }
            .show-path .dep-path {
                display: block;
            }
            .path-separator {
                margin: 0 3px;
                color: #999;
            }
        </style>
        <div class="search-container">
            <input type="text" class="search-box" id="tree-search" placeholder="搜索依赖...">
            <button class="search-button" id="search-btn" onclick="filterDependencies()">搜索</button>
            <button class="search-button" id="toggle-path-btn" style="margin-left: 5px;" onclick="togglePaths()">显示路径</button>
        </div>
        <div class="summary">
            依赖树总览: ${dependencies.length} 个依赖项，${rootDeps.length} 个根依赖项
        </div>
        <div class="tree-view" id="tree-container">
    `;
    
    for (const root of rootDeps) {
        const rootVersion = root.version?.trim() ? root.version : '未指定';
        const escapedScope = escapeHtmlFunc(root.scope ?? 'compile');
        const hasConflict = root.conflicts && root.conflicts.length > 0;
        const conflictClass = hasConflict ? ' conflict' : '';
        
        html += `
            <div class="root-dep" data-path="${escapeAttrValueFunc(root.path.join(':'))}" data-group-id="${escapeAttrValueFunc(root.groupId)}" data-artifact-id="${escapeAttrValueFunc(root.artifactId)}">
                <div class="dep-line${conflictClass}">
                    <span class="dep-name">${escapeHtmlFunc(root.groupId)}:${escapeHtmlFunc(root.artifactId)}</span>
                    <span class="dep-version">${escapeHtmlFunc(rootVersion)}</span>
                    <span class="dep-scope">${escapedScope}</span>
                    <div class="actions">
                        <button class="action-btn exclude-btn" data-group-id="${escapeAttrValueFunc(root.groupId)}" data-artifact-id="${escapeAttrValueFunc(root.artifactId)}" data-pom-path="${escapeAttrValueFunc(pomPath)}">排除</button>
                    </div>
                </div>
                <div class="dep-path" style="display: none;">
                    ${escapeHtmlFunc(root.groupId)}:${escapeHtmlFunc(root.artifactId)}:${escapeHtmlFunc(rootVersion)}
                </div>
                ${renderChildrenDependencies(dependencies, `${root.groupId}:${root.artifactId}`, pomPath, escapeHtmlFunc, escapeAttrValueFunc)}
            </div>
        `;
    }
    
    html += `</div>`;
    html += getSearchFilterScript();
    
    return html;
}

/**
 * 呈现子依赖项
 */
function renderChildrenDependencies(allDependencies: Dependency[], parentPath: string, pomPath: string, escapeHtmlFunc: (text: string) => string, escapeAttrValueFunc: (text: string) => string): string {
    // 筛选出父路径对应的子依赖项
    const children = allDependencies.filter(dep => 
        dep.path && 
        dep.path.length > 0 && 
        dep.path.join(':') === parentPath
    );
    
    if (!children || children.length === 0) {
        return '';
    }
    
    let html = '<div class="children-container">';
    
    for (const child of children) {
        const childVersion = child.version?.trim() ? child.version : '未指定';
        const hasConflict = child.conflicts && child.conflicts.length > 0;
        const conflictClass = hasConflict ? ' conflict' : '';
        const depPath = parentPath ? `${parentPath}:${child.groupId}:${child.artifactId}` : `${child.groupId}:${child.artifactId}`;
        
        html += `
            <div class="dep" data-path="${escapeAttrValueFunc(depPath)}" data-group-id="${escapeAttrValueFunc(child.groupId)}" data-artifact-id="${escapeAttrValueFunc(child.artifactId)}">
                <div class="dep-line${conflictClass}">
                    <span class="dep-name">${escapeHtmlFunc(child.groupId)}:${escapeHtmlFunc(child.artifactId)}</span>
                    <span class="dep-version">${escapeHtmlFunc(childVersion)}</span>
                    <span class="dep-scope">${escapeHtmlFunc(child.scope ?? 'compile')}</span>
                    <div class="actions">
                        <button class="action-btn exclude-btn" data-group-id="${escapeAttrValueFunc(child.groupId)}" data-artifact-id="${escapeAttrValueFunc(child.artifactId)}" data-pom-path="${escapeAttrValueFunc(pomPath)}">排除</button>
                    </div>
                </div>
                <div class="dep-path" style="display: none;">
                    ${escapeHtmlFunc(depPath)}:${escapeHtmlFunc(childVersion)}
                </div>
                ${renderChildrenDependencies(allDependencies, depPath, pomPath, escapeHtmlFunc, escapeAttrValueFunc)}
            </div>
        `;
    }
    
    html += '</div>';
    return html;
}

/**
 * 获取搜索过滤脚本
 */
function getSearchFilterScript(): string {
    return `
        <script>
            const vscode = acquireVsCodeApi();
            
            // 全局函数：排除依赖
            function excludeDependency(groupId, artifactId) {
                vscode.postMessage({
                    command: 'excludeDependency',
                    groupId: groupId,
                    artifactId: artifactId
                });
            }
            
            // 全局函数：加载更多子依赖
            function loadMoreChildDeps(parentId, parentPath, depth) {
                vscode.postMessage({
                    command: 'loadDependencyChildren',
                    parentId: parentId,
                    parentPath: parentPath,
                    depth: depth,
                    containerId: 'children-' + parentId
                });
            }

            document.getElementById('search-btn').addEventListener('click', function() {
                filterDependencies();
            });
            document.getElementById('tree-search').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    filterDependencies();
                }
            });
            // 显示/隐藏路径
            function togglePaths() {
                const container = document.getElementById('tree-container');
                if (container) {
                    container.classList.toggle('show-path');
                    const btn = document.getElementById('toggle-path-btn');
                    if (btn) {
                        btn.textContent = container.classList.contains('show-path') ? '隐藏路径' : '显示路径';
                    }
                }
            }
            function filterDependencies() {
                const searchInput = document.getElementById('tree-search');
                if (!searchInput) return;
                const searchTerm = searchInput.value.toLowerCase().trim();
                const container = document.getElementById('tree-container');
                if (!container) return;
                // 显示路径，搜索时始终显示路径
                container.classList.add('show-path');
                const pathBtn = document.getElementById('toggle-path-btn');
                if (pathBtn) {
                    pathBtn.textContent = '隐藏路径';
                }
                // 重置所有元素状态 - 首先移除所有高亮和类
                container.querySelectorAll('.search-match, .parent-of-match').forEach(el => {
                    el.classList.remove('search-match', 'parent-of-match');
                });
                // 移除之前的高亮内联样式
                container.querySelectorAll('span.search-match').forEach(el => {
                    if (el.parentElement) {
                        el.outerHTML = el.textContent || '';
                    }
                });
                // 重置所有节点显示状态
                const rootDeps = container.querySelectorAll('.root-dep');
                let hasVisibleItems = false;
                // 如果搜索条件为空，则重置显示所有元素
                if (!searchTerm) {
                    rootDeps.forEach(rootDep => {
                        rootDep.style.display = '';
                        const allDeps = rootDep.querySelectorAll('.dep');
                        allDeps.forEach(dep => {
                            dep.style.display = '';
                        });
                    });
                    // 移除无结果提示
                    const noResults = container.querySelector('.no-results');
                    if (noResults) {
                        noResults.remove();
                    }
                    return;
                }
                // 首先隐藏所有依赖
                rootDeps.forEach(rootDep => {
                    rootDep.style.display = 'none';
                    rootDep.querySelectorAll('.dep').forEach(dep => {
                        dep.style.display = 'none';
                    });
                });
                // 记录匹配的元素和需要显示的元素
                const matchedElements = new Set();
                const elementsToShow = new Set();
                // 搜索函数 - 检查元素文本是否匹配
                function searchInElement(element, selector, highlightMatch = true) {
                    const target = element.querySelector(selector);
                    if (!target) return false;
                    const text = target.textContent.toLowerCase();
                    if (!text.includes(searchTerm)) return false;
                    // 文本匹配
                    matchedElements.add(element);
                    // 高亮匹配文本
                    if (highlightMatch) {
                        const regex = new RegExp('(' + searchTerm.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&') + ')', 'gi');
                        const originalHtml = target.innerHTML;
                        const newHtml = originalHtml.replace(regex, '<span class="search-match">$1</span>');
                        if (newHtml !== originalHtml) {
                            target.innerHTML = newHtml;
                        }
                    }
                    return true;
                }
                // 递归添加所有父元素到显示集合
                function addParentChain(element) {
                    // 将元素添加到显示集合
                    elementsToShow.add(element);
                    // 直接父节点处理
                    const parentDep = element.parentElement?.closest('.dep, .root-dep');
                    if (parentDep && !elementsToShow.has(parentDep)) {
                        parentDep.classList.add('parent-of-match');
                        addParentChain(parentDep);
                    }
                    // 处理层级关系中的父节点 (根据数据属性)
                    const path = element.getAttribute('data-path');
                    if (path) {
                        const parts = path.split(':');
                        if (parts.length >= 4) {
                            // 构建父路径
                            for (let i = parts.length - 2; i >= 2; i -= 2) {
                                const parentPath = parts.slice(0, i).join(':');
                                const parentElements = container.querySelectorAll('.dep[data-path="' + parentPath + '"]');
                                parentElements.forEach(parentElement => {
                                    if (!elementsToShow.has(parentElement)) {
                                        parentElement.classList.add('parent-of-match');
                                        elementsToShow.add(parentElement);
                                    }
                                });
                            }
                        }
                    }
                }
                // 1. 首先搜索依赖名称
                rootDeps.forEach(rootDep => {
                    // 检查根依赖
                    const rootMatch = searchInElement(rootDep, '.dep-name');
                    if (rootMatch) {
                        rootDep.classList.add('search-match');
                        elementsToShow.add(rootDep);
                        hasVisibleItems = true;
                    }
                    // 检查子依赖 - 不管是否已经找到匹配项都继续搜索所有依赖
                    rootDep.querySelectorAll('.dep').forEach(depEl => {
                        const depMatch = searchInElement(depEl, '.dep-name');
                        if (depMatch) {
                            depEl.classList.add('search-match');
                            addParentChain(depEl);
                            hasVisibleItems = true;
                        }
                    });
                });
                // 2. 始终搜索依赖路径文本，确保找到既是一级依赖又是传递依赖的所有情况
                rootDeps.forEach(rootDep => {
                    // 检查根依赖路径
                    const rootPathMatch = searchInElement(rootDep, '.dep-path');
                    if (rootPathMatch) {
                        rootDep.classList.add('search-match');
                        elementsToShow.add(rootDep);
                        hasVisibleItems = true;
                    }
                    // 检查子依赖路径，即使已经找到了依赖名称匹配项
                    rootDep.querySelectorAll('.dep').forEach(depEl => {
                        const depPathMatch = searchInElement(depEl, '.dep-path');
                        if (depPathMatch) {
                            depEl.classList.add('search-match');
                            addParentChain(depEl);
                            hasVisibleItems = true;
                        }
                    });
                });
                // 3. 显示所有匹配元素及其父链
                elementsToShow.forEach(element => {
                    element.style.display = '';
                    // 确保根元素可见
                    const rootElement = element.closest('.root-dep');
                    if (rootElement) {
                        rootElement.style.display = '';
                    }
                });
                // 4. 处理无结果情况
                if (!hasVisibleItems) {
                    // 移除旧的无结果提示
                    const oldNoResults = container.querySelector('.no-results');
                    if (oldNoResults) {
                        oldNoResults.remove();
                    }
                    // 添加无结果提示
                    const noResults = document.createElement('div');
                    noResults.className = 'no-results';
                    noResults.innerText = '没有找到匹配 "' + searchTerm + '" 的依赖项';
                    container.appendChild(noResults);
                } else {
                    // 确保移除无结果提示
                    const noResults = container.querySelector('.no-results');
                    if (noResults) {
                        noResults.remove();
                    }
                }
            }
        </script>
    `;
}

/**
 * 生成简化分析器HTML
 */
export function generateSimplifiedAnalyzerHtml(dependencies: Dependency[], effectiveDependencies: Dependency[], pomPath: string, escapeHtmlFunc: (text: string) => string, escapeAttrValueFunc: (text: string) => string, extensionUri?: vscode.Uri): string {
    const conflicts = dependencies.filter(d => d.conflicts && d.conflicts.length > 0);
    const hasConflicts = conflicts.length > 0;
    
    // 定义HTML变量
    let html = '';
    
    // 使用带图标的样式，如果提供了extensionUri
    const styles = extensionUri ? 
        generateAnalyzerStylesWithIcons(extensionUri) : 
        `<style>
            body {
                font-family: var(--vscode-font-family);
                font-size: var(--vscode-font-size);
                color: var(--vscode-foreground);
                padding: 0;
                margin: 0;
            }
                .container {
                    padding: 15px;
                }
                h2 {
                    margin-top: 0;
                    border-bottom: 1px solid var(--vscode-panel-border);
                    padding-bottom: 10px;
                }
                .notification {
                    display: flex;
                    align-items: center;
                    padding: 10px;
                    margin-bottom: 15px;
                    border-radius: 4px;
                    background-color: var(--vscode-inputValidation-infoBackground);
                    color: var(--vscode-inputValidation-infoForeground);
                    border: 1px solid var(--vscode-inputValidation-infoBorder);
                }
                .notification.error {
                    background-color: var(--vscode-inputValidation-errorBackground);
                    color: var(--vscode-inputValidation-errorForeground);
                    border: 1px solid var(--vscode-inputValidation-errorBorder);
                }
                .notification-text {
                    margin-left: 10px;
                }
                .tab-container {
                    margin-bottom: 15px;
                }
                .tabs {
                    display: flex;
                    border-bottom: 1px solid var(--vscode-panel-border);
                }
                .tab {
                    padding: 8px 16px;
                    cursor: pointer;
                    border: 1px solid transparent;
                    border-bottom: none;
                    margin-right: 5px;
                    border-top-left-radius: 4px;
                    border-top-right-radius: 4px;
                }
                .tab.active {
                    border-color: var(--vscode-panel-border);
                    background-color: var(--vscode-editor-background);
                    border-bottom: 1px solid var(--vscode-editor-background);
                    margin-bottom: -1px;
                }
                .tab-content {
                    padding: 15px;
                    border: 1px solid var(--vscode-panel-border);
                    border-top: none;
                    display: none;
                }
                .tab-content.active {
                    display: block;
                }
                .conflicts-header {
                    color: var(--vscode-errorForeground);
                }
                .no-conflicts {
                    padding: 20px;
                    text-align: center;
                    color: var(--vscode-disabledForeground);
                }
                table {
                    width: 100%;
                    border-collapse: collapse;
                }
                th, td {
                    padding: 8px;
                    text-align: left;
                    border-bottom: 1px solid var(--vscode-panel-border);
                }
                th {
                    background-color: var(--vscode-editor-inactiveSelectionBackground);
                    position: sticky;
                    top: 0;
                }
                tr:hover {
                    background-color: var(--vscode-list-hoverBackground);
                }
                .action-btn {
                    background: none;
                    border: none;
                    cursor: pointer;
                    color: var(--vscode-textLink-foreground);
                    padding: 2px 5px;
                    text-decoration: underline;
                }
                .load-more-container {
                    text-align: center;
                    padding: 10px;
                    margin-top: 10px;
                }
                .load-more-btn {
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    padding: 6px 12px;
                    cursor: pointer;
                    border-radius: 2px;
                }
                .load-more-btn:hover {
                    background-color: var(--vscode-button-hoverBackground);
                }
                .version-cell {
                    font-weight: bold;
                }
                .search-container {
                    display: flex;
                    margin-bottom: 10px;
                }
                .search-input {
                    flex: 1;
                    padding: 6px;
                    border: 1px solid var(--vscode-input-border);
                    background-color: var(--vscode-input-background);
                    color: var(--vscode-input-foreground);
                }
                .search-btn {
                    margin-left: 5px;
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    padding: 6px 12px;
                    cursor: pointer;
                }
                .refresh-btn {
                    margin-left: auto;
                    background-color: var(--vscode-button-background);
                    color: var(--vscode-button-foreground);
                    border: none;
                    padding: 6px 12px;
                    cursor: pointer;
                }
                .hidden {
                    display: none;
                }
                .conflict-badge {
                    display: inline-block;
                    background-color: var(--vscode-inputValidation-errorBackground);
                    color: var(--vscode-inputValidation-errorForeground);
                    border-radius: 10px;
                    padding: 2px 8px;
                    font-size: 0.8em;
                    margin-left: 8px;
                }
            </style>
        </head>
        <body>
            <div class="container">
                <h2>依赖分析 - ${escapeHtmlFunc(pomPath)}</h2>
                
                ${hasConflicts ? `
                <div class="notification error">
                    <span class="notification-text">发现 ${conflicts.length} 个依赖冲突！</span>
                </div>
                ` : ''}

                <div class="tab-container">
                    <div class="tabs">
                        <div class="tab active" data-tab="dependencies">
                            <span class="icon dependency-icon"></span>所有依赖 <span class="badge">${dependencies.length}</span>
                        </div>
                        <div class="tab" data-tab="tree">
                            <span class="icon tree-icon"></span>依赖树
                        </div>
                        ${hasConflicts ? `<div class="tab" data-tab="conflicts">
                            <span class="icon conflict-icon"></span>冲突 <span class="conflict-badge">${conflicts.length}</span>
                        </div>` : ''}
                    </div>
                    
                    <div class="tab-content active" id="dependencies-tab">
                        <div class="search-container">
                            <input type="text" class="search-input" id="dependency-search" placeholder="搜索依赖...">
                            <button class="search-btn" id="search-dependencies-btn">搜索</button>
                            <button class="refresh-btn" id="refresh-dependencies-btn">刷新</button>
                        </div>
                        <div id="dependencies-container">
                            ${generateDependenciesTableHtml(dependencies, pomPath, escapeHtmlFunc)}
                        </div>
                    </div>
                    
                    <div class="tab-content" id="tree-tab">
                        ${generateSimplifiedDependencyTreeHtml(effectiveDependencies, pomPath, escapeHtmlFunc, escapeAttrValueFunc)}
                    </div>
                    
                    ${hasConflicts ? `
                    <div class="tab-content" id="conflicts-tab">
                        <h3 class="conflicts-header">依赖冲突</h3>
                        <div id="conflicts-container">
                            ${generateConflictsTableHtml(conflicts, pomPath, escapeHtmlFunc, escapeAttrValueFunc)}
                        </div>
                    </div>
                    ` : ''}
                </div>
            </div>
            
            ${getGlobalFunctionsScript()}
            <!-- 添加调试辅助代码 -->
            <script>
                // 调试辅助函数
                window._debug = {
                    checkElements: function() {
                        const treeTab = document.querySelector('.tab[data-tab="tree"]');
                        console.log('依赖树标签:', treeTab);
                        
                        const treeContent = document.getElementById('tree-tab');
                        console.log('依赖树内容区域:', treeContent);
                        
                        const allTabs = Array.from(document.querySelectorAll('.tab'));
                        console.log('所有标签:', allTabs.map(tab => ({
                            dataTab: tab.getAttribute('data-tab'),
                            isActive: tab.classList.contains('active'),
                            text: tab.textContent.trim()
                        })));
                        
                        const allContents = Array.from(document.querySelectorAll('.tab-content'));
                        console.log('所有内容区域:', allContents.map(content => ({
                            id: content.id,
                            isActive: content.classList.contains('active'),
                            hasContent: content.innerHTML.length > 10
                        })));
                    },
                    
                    forceLoadTree: function() {
                        const vscode = acquireVsCodeApi();
                        console.log('强制加载依赖树内容...');
                        vscode.postMessage({
                            command: 'loadTab',
                            tab: 'tree'
                        });
                    }
                };
            </script>
            <script>
                // 确保vscode API已准备好
                const vscode = acquireVsCodeApi();
                
                // 在页面加载完成后立即发送webviewReady消息
                console.log('页面开始加载，立即发送webviewReady消息');
                try {
                    vscode.postMessage({
                        command: 'webviewReady'
                    });
                } catch (err) {
                    console.error('发送初始webviewReady消息失败:', err);
                }
                
                (function() {
                    // 标签切换
                    document.querySelectorAll('.tab').forEach(tab => {
                        tab.addEventListener('click', () => {
                            const tabId = tab.getAttribute('data-tab');
                            
                            // 更新标签激活状态
                            document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                            tab.classList.add('active');
                            
                            // 更新内容显示
                            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                            document.getElementById(tabId + '-tab').classList.add('active');
                            
                            // 向扩展发送加载标签内容的消息
                            console.log('发送loadTab消息:', tabId);
                            vscode.postMessage({
                                command: 'loadTab',
                                tab: tabId
                            });
                        });
                    });
                    
                    // 所有按钮事件处理
                    document.addEventListener('click', (e) => {
                        if (e.target.classList.contains('exclude-btn')) {
                            const groupId = e.target.getAttribute('data-group-id');
                            const artifactId = e.target.getAttribute('data-artifact-id');
                            const pomPath = e.target.getAttribute('data-pom-path');
                            
                            console.log('点击排除按钮:', groupId, artifactId, pomPath);
                            
                            // 向扩展发送排除依赖命令
                            vscode.postMessage({
                                command: 'excludeDependency',
                                groupId: groupId,
                                artifactId: artifactId,
                                pomPath: pomPath
                            });
                        }
                        else if (e.target.classList.contains('load-more-btn')) {
                            const parentId = e.target.getAttribute('data-parent-id');
                            const parentPath = e.target.getAttribute('data-parent-path');
                            const depth = parseInt(e.target.getAttribute('data-depth') || '0', 10);
                            
                            console.log('点击加载子依赖按钮:', parentId, parentPath, depth);
                            
                            // 向扩展发送加载子依赖命令
                            vscode.postMessage({
                                command: 'loadDependencyChildren',
                                parentId: parentId,
                                parentPath: parentPath,
                                depth: depth,
                                containerId: 'children-' + parentId
                            });
                        }
                        else if (e.target.classList.contains('view-details-btn')) {
                            const groupId = e.target.getAttribute('data-group-id');
                            const artifactId = e.target.getAttribute('data-artifact-id');
                            const path = e.target.getAttribute('data-path');
                            const id = e.target.getAttribute('data-id');
                            
                            // 向扩展发送查看依赖详情命令
                            vscode.postMessage({
                                command: 'viewDependencyDetails',
                                groupId: groupId,
                                artifactId: artifactId,
                                path: path,
                                id: id
                            });
                        }
                    });
                    
                    // 搜索依赖
                    document.getElementById('search-dependencies-btn').addEventListener('click', () => {
                        searchDependencies();
                    });
                    
                    document.getElementById('dependency-search').addEventListener('keypress', (e) => {
                        if (e.key === 'Enter') {
                            searchDependencies();
                        }
                    });
                    
                    function searchDependencies() {
                        const searchTerm = document.getElementById('dependency-search').value.toLowerCase().trim();
                        
                        vscode.postMessage({
                            command: 'searchDependencies',
                            searchTerm: searchTerm
                        });
                    }
                    
                    // 刷新依赖
                    document.getElementById('refresh-dependencies-btn').addEventListener('click', () => {
                        vscode.postMessage({
                            command: 'refreshDependencies',
                            pomPath: '${escapeAttrValueFunc(pomPath)}'
                        });
                    });
                    
                    // 加载更多依赖
                    const loadMoreBtn = document.getElementById('load-more');
                    if (loadMoreBtn) {
                        loadMoreBtn.addEventListener('click', () => {
                            vscode.postMessage({
                                command: 'loadMoreDependencies'
                            });
                        });
                    }
                    
                    // 通知扩展页面已加载完成
                    console.log('页面初始化完成，发送webviewReady消息');
                    
                    // 确保立即发送并且不会错过，先设置一个短延迟，然后增加重试机制
                    setTimeout(() => {
                        try {
                            console.log('发送webviewReady消息 - 第1次尝试');
                            vscode.postMessage({
                                command: 'webviewReady'
                            });
                            
                            // 增加重试机制确保消息能被接收
                            setTimeout(() => {
                                console.log('发送webviewReady消息 - 第2次尝试（重试）');
                                vscode.postMessage({
                                    command: 'webviewReady'
                                });
                            }, 500);
                        } catch (err) {
                            console.error('发送webviewReady消息失败:', err);
                        }
                    }, 200); // 延迟200ms确保页面完全渲染
                })();
            </script>
        </body>
        </html>
    `;
    
    return html;
}

/**
 * 生成分析器视图的CSS样式，包含图标样式
 */
export function generateAnalyzerStylesWithIcons(extensionUri: vscode.Uri): string {
    // 构建图标的资源URI
    const dependencyIconPath = vscode.Uri.joinPath(extensionUri, 'resources', 'icons', 'dependency-icon.svg');
    const conflictIconPath = vscode.Uri.joinPath(extensionUri, 'resources', 'icons', 'conflict-icon.svg');
    const treeIconPath = vscode.Uri.joinPath(extensionUri, 'resources', 'icons', 'tree-icon.svg');
    const mavenIconPath = vscode.Uri.joinPath(extensionUri, 'resources', 'icons', 'maven-icon.svg');
    
    return `
        <style>
            body {
                font-family: var(--vscode-font-family);
                font-size: var(--vscode-font-size);
                color: var(--vscode-foreground);
                background-color: var(--vscode-editor-background);
                padding: 10px;
                margin: 0;
            }
            .container {
                max-width: 100%;
                margin: 0 auto;
            }
            h1, h2, h3 {
                color: var(--vscode-editor-foreground);
                border-bottom: 1px solid var(--vscode-panel-border);
                padding-bottom: 5px;
            }
            .tab-container {
                border-bottom: 1px solid var(--vscode-panel-border);
                margin-bottom: 20px;
            }
            .tab-button {
                background-color: var(--vscode-button-secondaryBackground);
                color: var(--vscode-button-secondaryForeground);
                border: none;
                padding: 8px 16px;
                cursor: pointer;
                font-size: 14px;
                margin-right: 4px;
                border-radius: 4px 4px 0 0;
                position: relative;
            }
            .tab-button.active {
                background-color: var(--vscode-button-background);
                color: var(--vscode-button-foreground);
                font-weight: bold;
            }
            .tab-button:hover:not(.active) {
                background-color: var(--vscode-button-secondaryHoverBackground);
            }
            .tab-button .icon {
                margin-right: 6px;
                vertical-align: middle;
                display: inline-block;
                width: 16px;
                height: 16px;
                background-size: contain;
                background-repeat: no-repeat;
                background-position: center;
            }
            .tab-button .dependency-icon {
                background-image: url(${dependencyIconPath});
            }
            .tab-button .conflict-icon {
                background-image: url(${conflictIconPath});
            }
            .tab-button .tree-icon {
                background-image: url(${treeIconPath});
            }
            .tab-content {
                display: none;
                padding: 10px;
                border: 1px solid var(--vscode-panel-border);
                border-top: none;
                background-color: var(--vscode-editor-background);
                margin-top: -1px;
            }
            .tab-content.active {
                display: block;
            }
            .badge {
                background-color: var(--vscode-badge-background);
                color: var(--vscode-badge-foreground);
                border-radius: 10px;
                padding: 2px 8px;
                font-size: 12px;
                position: relative;
                top: -1px;
                margin-left: 4px;
            }
            /* 保留其他现有样式... */
        </style>
    `;
}
